var historyAdaptor = new Object();

var Logger = {
	clear : function() {
		$('#history-log').val("");
	},
	append : function(text) {
		var dom = $('#history-log').get(0);
		dom.value += text + "\n";
		dom.scrollTop = dom.scrollHeight;
	}
};

/**
 * History call back. Load new content form server by AJAX.
 * 
 * @param anchor
 */

function pageload(hash) {
	Logger.append("[callback called] hash=" + hash);
	if (hash) {
		/*
		 * var parts = decodeURIComponent(anchor).split('?'); var path =
		 * parts.shift(); var setClosed = false; if (parts.length) { var param =
		 * parts.shift(); if (param == 'state=closed') { setClosed = true; } }
		 * _selectDir(path, setClosed);
		 */
		$("#load").text("loaded: " + hash);
	} else {
		// start page
		$("#load").empty();
	}
	$('#hash-input').val(hash);
};

/**
 * Initialize and use browser history
 */
$(document).ready(
		function() {
			$("#treePages").treeview();

			if ($.browser.msie && $.browser.version == 8) {
				$('#ie-info').text(
						'You are using IE8 in version ' + document.documentMode
								+ ' compatible mode.');
			}
			$('#type-info').text(
					'The plugin is running in ' + $.history.type + ' mode.');

			$.history.init(pageload);

			$(".history-links a").click(function() {
				var href = $(this).attr('href');
				hash = href.replace(/^.*?#/, '');
				Logger.append("[link clicked] href=" + href);
				loadHistory(hash);
				return false;
			});

			$('#load-hash').click(function() {
				var hash = $('#hash-input').val();
				if (hash) {
					loadHistory(hash);
				}
			});
		});

function loadHistory(hash) {
	Logger.append('[load history] hash=' + hash);
	$.history.load(hash);
}

function initMenuTree(jsonTree) {
	historyAdaptor.menuTree = jsonTree;

	var topNodeHtml = document.getElementById("topnode");
	updateHtmlNodeFromJson(topNodeHtml, jsonTree.topnode, false);
}

function updateHtmlNodeFromJson(nodeLiHtml, nodeModel, isNeedAddLiHtmlToTree) {
	nodeModel.needLoad = false;
	nodeLiHtml.nodeModel = nodeModel;
	for ( var x = 0; nodeLiHtml.childNodes[x]; x++) {
		var child = nodeLiHtml.childNodes[x];
		if (child.nodeName.toLowerCase() == "ul") {
			for ( var x1 = 0; child.childNodes[x1]; x1++) {
				var subChild = child.childNodes[x1];
				if (subChild.nodeName.toLowerCase() == "li") {
					var subnodeModel = nodeModel.subnodes[$(subChild)
							.attr("id")];
					addSubnodesRecursively(subChild, subnodeModel, false,
							isNeedAddLiHtmlToTree);
					if (isNeedAddLiHtmlToTree) {
						$("#treePages").treeview({
							add : $(subChild)
						});
					}
				}
			}
		}
	}
}

var currentSelectedTreeNodeSpan = null;

function selectNode(event, nodeHtmlEl) {
	// IE
	if ($.browser.msie) {
		window.event.cancelBubble = true;
	}
	if (event.stopPropagation) {
		event.stopPropagation();
	}

	// select element
	if (currentSelectedTreeNodeSpan) {
		currentSelectedTreeNodeSpan.removeClass("selected");
	}
	var spanHtmlEl = $("span", nodeHtmlEl).get(0);
	var spanTreeNode = $(spanHtmlEl);
	spanTreeNode.addClass("selected");
	currentSelectedTreeNodeSpan = spanTreeNode;

	var needLoad = nodeHtmlEl.nodeModel.needLoad;
	if (needLoad) {
		//alert("NeedLoad!!!");
		updateMenuNode(nodeHtmlEl);
	}
	var nodePath = getNodeHash(nodeHtmlEl);
	Logger.append("[link clicked] needLoad " + needLoad + "; href=" + nodePath);
	loadHistory(nodePath);
}

function getNodeHash(nodeHtmlEl) {
	var nodePath = nodeHtmlEl.nodeModel.path;
	if ($(nodeHtmlEl).hasClass("expandable")) {
		nodePath = nodePath + "?state=closed";
	}
	return nodePath;
}

function addSubnodesRecursively(nodeLiHtml, nodeModel, isLiNew,
		isNeedAddLiHtmlToTree) {
	nodeLiHtml.nodeModel = nodeModel;
	if (isLiNew) {
		var spanHtml = document.createElement("span");
		spanHtml.setAttribute("class", "menu");
		var subNodeText = document.createTextNode(nodeModel.title);
		spanHtml.appendChild(subNodeText);
		nodeLiHtml.appendChild(spanHtml);
	}

	var ulHtml;
	for (var subnodeId in nodeModel.subnodes) {
		if (!ulHtml) {
			ulHtml = document.createElement("ul");
			nodeLiHtml.appendChild(ulHtml);
		}
		var subNodeModel = nodeModel.subnodes[subnodeId];
		if (!subNodeModel.subnodes) {
			// need loaded node
			nodeModel.needLoad = true;
		}
		var subLiHtml = document.createElement("li");
		subLiHtml.setAttribute("id", subnodeId);
		subLiHtml.setAttribute("onclick", "selectNode(event, this);");
		subLiHtml.setAttribute("class", "closed");
		ulHtml.appendChild(subLiHtml);
		addSubnodesRecursively(subLiHtml, subNodeModel, true,
				isNeedAddLiHtmlToTree);
	}
}

function updateMenuNode(nodeLiHtml) {
	var nodeModel = nodeLiHtml.nodeModel;
	$.ajax({
		url : "pages/feedMenuNode",
		dataType : "json",
		data : {
			"path" : nodeModel.path
		},
		success : function(data) {
			Logger.append(data);
			updateHtmlNodeFromJson(nodeLiHtml, data, true);
		}

	});

}
